<template>
  <div class="goods-image">
    <!-- 右边的大图 -->
    <div v-show="!isOutside" class="large"
      :style="{backgroundImage: `url(${images[curIndex]})`, ...bgPosition}"></div>
    <!-- 左边的中图 -->
    <div class="middle" ref="target">
      <img :src="images[curIndex]" alt="">
      <!-- 放大镜遮罩层 -->
      <div v-show="!isOutside" class="layer" :style="layerStyle"></div>
    </div>
    <!-- 小图 -->
    <ul class="small">
      <li v-for="(img,idx) in images" :key="img" :class="{active:idx===curIndex}">
        <img @click="curIndex=idx" :src="img" alt="">
      </li>
    </ul>
  </div>
</template>
<script>
import { ref, watch, reactive } from 'vue'
import { useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  props: {
    images: { type: Array, default: () => [] }
  },
  setup (props) {
    // 显示图片的下标
    const curIndex = ref(0)
    // 以绑定的元素为基准，计算鼠标的位置
    const target = ref(null)
    const { elementX, elementY, isOutside } = useMouseInElement(target)
    // 遮罩的位置
    const layerStyle = reactive({ top: 0, left: 0 })
    // 定义放大指定的位置
    const bgPosition = reactive({
      'background-position-x': 0, // 精准的css样式的名字，方便直接使用
      'background-position-y': 0
    })
    watch([elementX, elementY, isOutside], () => {
      let top = elementY.value - 100
      let left = elementX.value - 100
      if (top > 200) top = 200
      if (left > 200) left = 200
      if (top < 0) top = 0
      if (left < 0) left = 0

      layerStyle.top = top + 'px'
      layerStyle.left = left + 'px'
      // 给右边大图设置background-position的值
      bgPosition['background-position-x'] = (-2 * left) + 'px'
      bgPosition['background-position-y'] = (-2 * top) + 'px'
    })

    return { curIndex, target, elementX, elementY, isOutside, layerStyle, bgPosition }
  }
}
</script>
<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
